package com.apes.framework.plugin.filereader;

import com.apes.framework.util.FileUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 功能：Esb文件解析器
 *
 * @author xul
 * @create 2017-12-05 14:05
 */
public abstract class FileReader implements Reader {
    protected final Log logger = LogFactory.getLog(this.getClass());

    @Override
    public void read() {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            for (String pkg : getPackages()) {
                Enumeration<URL> urls = loader.getResources(pkg.replaceAll("\\.", "/")); /**按文件的形式去查找**/
                while (urls.hasMoreElements()) {
                    URL url = urls.nextElement();
                    if (url != null) {
                        String protocol = url.getProtocol();
                        if ("file".equals(protocol)) {
                            refreshFile(url.getPath());
                        } else if ("jar".equals(protocol)) {
                            refreshJarFile((JarURLConnection) url.openConnection());
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }

    public void refreshJarFile(JarURLConnection connection) throws Exception {
        JarFile jarFile = connection.getJarFile();
        try {
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String entryName = entry.getName().toLowerCase();
                if (entryName.endsWith(getSuffix())) {
                    InputStream is = jarFile.getInputStream(entry);
                    parse(is, entryName);
                }
            }
        } finally {
            jarFile.close();
        }
    }

    public void refreshFile(String strPath) {
        try {
            strPath = URLDecoder.decode(strPath, "utf-8");//解决路径有空格问题
            File dir = new File(strPath);
            File[] files = dir.listFiles();
            if (files == null) return;
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    refreshFile(files[i].getAbsolutePath());
                } else {
                    String[] paths = files[i].getAbsolutePath().split("classes");
                    InputStream is = FileUtil.getInputStream(paths, getSuffix());
                    if(is != null) parse(is, files[i].getAbsolutePath());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }

    /**
     * 功能：文件解析
     */
    public abstract void parse(InputStream is, String fileAbsolutePath) throws Exception;
}
